package cn.cyh.queue_service.controller;

import cn.cyh.queue_service.common.Result;
import cn.cyh.queue_service.common.ResultCode;
import cn.cyh.queue_service.model.dto.PageRequest;
import cn.cyh.queue_service.model.dto.PageResult;
import cn.cyh.queue_service.model.dto.WindowRequest;
import cn.cyh.queue_service.model.entity.Window;
import cn.cyh.queue_service.model.vo.WindowVO;
import cn.cyh.queue_service.service.WindowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 窗口管理控制器
 */
@RestController
@RequestMapping("/windows")
@Tag(name = "窗口管理", description = "窗口管理相关接口")
@Slf4j
@RequiredArgsConstructor
public class WindowController {

    private final WindowService windowService;
    
    /**
     * 分页获取窗口列表
     *
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param name 窗口名称（可选）
     * @param status 状态（可选）
     * @param serviceTypeId 业务类型ID（可选）
     * @return 窗口列表分页结果
     */
    @GetMapping("getList")
    @Operation(summary = "分页获取窗口列表", description = "分页获取窗口列表，支持按名称、状态和业务类型筛选")
    public Result<PageResult<WindowVO>> getWindowList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "窗口名称") @RequestParam(required = false) String name,
            @Parameter(description = "状态：OPEN-开放, PAUSE-暂停, CLOSED-关闭") @RequestParam(required = false) String status,
            @Parameter(description = "业务类型ID") @RequestParam(required = false) Long serviceTypeId) {
        
        log.info("获取窗口列表: pageNum={}, pageSize={}", pageNum, pageSize);
        
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);
        pageRequest.addFilter("name", name);
        pageRequest.addFilter("status", status);
        pageRequest.addFilter("serviceTypeId", serviceTypeId);
        
        PageResult<WindowVO> pageResult = windowService.getWindowList(pageRequest);
        return Result.success(pageResult);
    }
    
    /**
     * 获取所有开放状态的窗口
     *
     * @return 窗口列表
     */
    @GetMapping("/open")
    @Operation(summary = "获取所有开放状态的窗口", description = "获取所有开放状态的窗口列表")
    public Result<List<WindowVO>> getOpenWindows() {
        log.info("获取所有开放状态的窗口");
        List<WindowVO> windows = windowService.getOpenWindows();
        return Result.success(windows);
    }
    
    /**
     * 根据ID获取窗口详情
     *
     * @param id 窗口ID
     * @return 窗口详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取窗口详情", description = "根据窗口ID获取窗口详情")
    public Result<WindowVO> getWindowById(@Parameter(description = "窗口ID") @PathVariable Long id) {
        log.info("获取窗口详情: id={}", id);
        WindowVO windowVO = windowService.getWindowById(id);
        return Result.success(windowVO);
    }
    
    /**
     * 创建窗口
     *
     * @param request 窗口请求
     * @return 新创建的窗口ID
     */
    @PostMapping("createWindow")
    @Operation(summary = "创建窗口", description = "创建新的窗口")
//    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<Long> createWindow(@Valid @RequestBody WindowRequest request) {
        log.info("创建窗口: {}", request.getName());
        Long id = windowService.createWindow(request);
        return Result.success(id);
    }
    
    /**
     * 更新窗口
     *
     * @param id 窗口ID
     * @param request 窗口请求
     * @return 更新结果
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新窗口", description = "根据窗口ID更新窗口")
//    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN')")
    public Result<Boolean> updateWindow(
            @Parameter(description = "窗口ID") @PathVariable Long id,
            @Valid @RequestBody WindowRequest request) {
        
        log.info("更新窗口: id={}", id);
        boolean result = windowService.updateWindow(id, request);
        return Result.success(result);
    }
    
    /**
     * 删除窗口
     *
     * @param id 窗口ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除窗口", description = "根据窗口ID删除窗口")
    public Result<Boolean> deleteWindow(@Parameter(description = "窗口ID") @PathVariable Long id) {
        log.info("删除窗口: id={}", id);
        boolean result = windowService.deleteWindow(id);
        return Result.success(result);
    }
    
    /**
     * 更新窗口状态
     *
     * @param id 窗口ID
     * @param status 状态
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "更新窗口状态", description = "根据窗口ID更新窗口状态")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN', 'OPERATOR')")
    public Result<Boolean> updateStatus(
            @Parameter(description = "窗口ID") @PathVariable Long id,
            @Parameter(description = "状态：OPEN-开放, PAUSE-暂停, CLOSED-关闭") @RequestParam String status) {
        
        log.info("更新窗口状态: id={}, status={}", id, status);
        
        if (!status.equals("OPEN") && !status.equals("PAUSE") && !status.equals("CLOSED")) {
            return Result.failed(ResultCode.PARAM_ERROR, "状态值只能为OPEN、PAUSE或CLOSED");
        }
        
        boolean result = windowService.updateStatus(id, status);
        return Result.success(result);
    }
    
    /**
     * 更新窗口当前服务的业务类型
     *
     * @param id 窗口ID
     * @param serviceTypeId 业务类型ID
     * @return 更新结果
     */
    @PutMapping("/{id}/service-type")
    @Operation(summary = "更新窗口业务类型", description = "根据窗口ID更新窗口当前服务的业务类型")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPERADMIN', 'OPERATOR')")
    public Result<Boolean> updateServiceType(
            @Parameter(description = "窗口ID") @PathVariable Long id,
            @Parameter(description = "业务类型ID") @RequestParam Long serviceTypeId) {
        
        log.info("更新窗口业务类型: id={}, serviceTypeId={}", id, serviceTypeId);
        boolean result = windowService.updateServiceType(id, serviceTypeId);
        return Result.success(result);
    }
    
    /**
     * 获取指定业务类型的可用窗口列表
     *
     * @param serviceTypeId 业务类型ID
     * @return 窗口列表
     */
    @GetMapping("/available")
    @Operation(summary = "获取可用窗口列表", description = "获取指定业务类型的可用窗口列表")
    public Result<List<Window>> getAvailableWindowsByServiceType(
            @Parameter(description = "业务类型ID") @RequestParam Long serviceTypeId) {
        
        log.info("获取业务类型可用窗口: serviceTypeId={}", serviceTypeId);
        List<Window> windows = windowService.getAvailableWindowsByServiceType(serviceTypeId);
        return Result.success(windows);
    }
} 